module ListenForClientCallHelper
  def devices_filename
    "db/devices"
  end
  
  def schedule_filename
    "db/scheduled_actions"
  end

  def config_filename
    TriggerSwitchD::ConfigFactory::ProperEnvironmentFile.new.path
  end
  
  def prepare_devices(device_name,device1,device2)
    __recreate_db_dir__
    dev = []
    dev = __load_existing_devices__ if File.exist? devices_filename
    new_switches = [device1,device2].map do |device|
      device.split(",").flatten
    end.map do |device|
      {"house_code" => device[0], "unit_code" => device[1], "model_name" => device[2]}
    end
    dev << {"name" => device_name, "switches" => new_switches}
    file = File.open(devices_filename,"w+")
    YAML::dump(dev,file)
    file.close
  end

  def prepare_config
    file = File.open(config_filename,"w+")
    file.puts <<-EOS
    Config.geo_position = {:north => 54.57525, :west => -12.94125}
    Config.log_path = "log"
    Config.db_path = "db"
    Config.dsl_path = "config"
    Config.vcp_port = "/dev/tty.usbserial-A6008UFF"
    Config.log_object = :spec
    Config.output = :spec
    Config.unix_socket_path = "/tmp"
    EOS
    file.close
  end
  
  def prepare_schedule(action)
    __recreate_db_dir__
    actions = ["#{action}\n"]
    file = File.open(schedule_filename,"a+")
    file.write(actions)
    file.close
  end
  
  private
  
  def __recreate_db_dir__
    Dir.mkdir("db") unless File.directory? "db"
  end
  
  def __load_existing_devices__
    file = File.open(devices_filename,"r")
    devices = TriggerSwitchD::load_devices(file)
    file.close
    devices.map do |device|
      switches = device[1].map do |switch|
        {"house_code" => switch.house_code, "unit_code" => switch.unit_code, "model_name" => switch.model_name}
      end
      {"name" => device[0], "switches" => switches}
    end
  end
  
end
World(ListenForClientCallHelper)